package com.kayeah82.application.avatar.qq.configuration;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author kayeah82
 * */
@Configuration
class RedisConfig {

    @Bean
    @ConfigurationProperties(prefix = "redis.master")
    public RedisSettings masterRedisSettings(){
        return new RedisSettings();
    }

    @Bean
    @Primary
    public RedisConnectionFactory redisConnectionFactory(@Qualifier(value = "masterRedisSettings") RedisSettings redisSettings) {
        return this.buildRedisConnectionFactory(redisSettings);
    }

    @Bean
    @Primary
    public RedisTemplate<?, ?> redisTemplate(@Qualifier(value = "redisConnectionFactory") RedisConnectionFactory redisConnectionFactory) {
        return new StringRedisTemplate(redisConnectionFactory);
    }

    private RedisConnectionFactory buildRedisConnectionFactory(RedisSettings redisSettings) {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(redisSettings.getHost(), redisSettings.getPort());

        if (StringUtils.isNotEmpty(redisSettings.getPassword())) {
            configuration.setPassword(redisSettings.getPassword());
        }

        if (redisSettings.getDatabase() != null) {
            configuration.setDatabase(redisSettings.getDatabase());
        }

        return new LettuceConnectionFactory(configuration);
    }


    /**
     * redis参数对象
     * */
    static class RedisSettings {

        private String host;
        private Integer port;
        private String password;
        private Integer database;

        public String getHost() {
            return host;
        }

        public void setHost(String host) {
            this.host = host;
        }

        public Integer getPort() {
            return port;
        }

        public void setPort(Integer port) {
            this.port = port;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public Integer getDatabase() {
            return database;
        }

        public void setDatabase(Integer database) {
            this.database = database;
        }
    }

}
